package cn.quang.search.toolkit.component.items.impl;

import cn.quang.search.toolkit.component.AbstractSearchItem;
import cn.quang.search.toolkit.component.constants.Constants;
import cn.quang.search.toolkit.enums.DataSourceTypeEnum;
import cn.quang.search.toolkit.enums.SearchOperator;
import cn.quang.search.toolkit.provider.entity.KeyOperatorValue;
import cn.quang.search.toolkit.provider.entity.QuerySlice;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SearchItem extends AbstractSearchItem {

    private final Object value;

    public <T> SearchItem(DataSourceTypeEnum dsType, String col, SearchOperator operator, T value){
        super(dsType, col, operator);
        this.value = value;
    }


    @Override
    public QuerySlice getQuerySlice() {
        String sqlTemplate;
        List<String> operators = new ArrayList<>();
        List<Object> values = new ArrayList<>();
        if (this.value == null) {
            if(dsType == DataSourceTypeEnum.ES) {
                sqlTemplate = String.format("%s%s", Constants.FIELD, " is missing ");
            } else if(dsType == DataSourceTypeEnum.MYSQL) {
                sqlTemplate = String.format("%s%s", Constants.FIELD, " is null ");
            } else {
                throw new IllegalArgumentException("不支持的数据源！");
            }
        } else {
            sqlTemplate = String.format("%s %s %s", Constants.FIELD, Constants.OPERATOR, Constants.VALUE);
            operators.add(this.operator.getOperator());
            values.add(value);
        }

        return QuerySlice.of(
                sqlTemplate,
                KeyOperatorValue.of(col, Collections.singletonList(this.col), operators, values)
        );
    }

}
